/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dal;

import dto.QuanTriDTO;
import dto.ThiSinhDTO;
import java.sql.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Stanley
 */
public class TaiKhoanDAO {

    public ThiSinhDTO getThiSinh(String cmnd) {
        Connection connection = SqlDatabase.getInstance();
        try {
            Statement query = (Statement) connection.createStatement();

            ResultSet rs = query.executeQuery("select * from thisinh where cmnd = '" + cmnd + "'");

            if (rs.next()) {
                // new dto
                return new ThiSinhDTO(rs.getInt("maTS"), rs.getString("cmnd"), rs.getString("hoten"), null);
            }
        } catch (SQLException ex) {
            Logger.getLogger(TaiKhoanDAO.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return null;
    }

    public QuanTriDTO getQuanTri(String username, String password) {
        Connection connection = SqlDatabase.getInstance();
        try {
            Statement query = (Statement) connection.createStatement();
            ResultSet rs = query.executeQuery("select * from quantri where username = '" + username + "' and password = '" + password + "'");

            if (rs.next()) {
                // new dto
                return new QuanTriDTO(rs.getInt("id"), rs.getString("username"), rs.getString("password"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(TaiKhoanDAO.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return null;
    }

    public boolean insertThiSinh(ThiSinhDTO info) {
        String dateOfBirth = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(info.getNgaysinh());
        Connection connection = SqlDatabase.getInstance();
        try {
            Statement query = (Statement) connection.createStatement();
            int result = query.executeUpdate("insert into thisinh (hoten, cmnd, ngaysinh) values ('"
                    + info.getHoten() + "' , '" + info.getCmnd() + "' , '" + dateOfBirth + "')");
            return result == 0 ? false : true;
        } catch (SQLException ex) {
            Logger.getLogger(TaiKhoanDAO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
}
